package com.hemaapp.yjnh.activity;

import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;

import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.bean.SysInitInfo;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseLocation;
import com.hemaapp.yjnh.BaseNetWorker;
import com.hemaapp.yjnh.R;

/**
 * 启动页
 */
public class StartActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_start);
		super.onCreate(savedInstanceState);
        new Handler().postDelayed(new Runnable() {//等待5秒后，再初始化
            @Override
            public void run() {
                IntentFilter filter = new IntentFilter();
                filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
                mContext.registerReceiver(netChangeReceiver, filter);
            }
        }, 1200);
		init();
		BaseLocation.getInstance(this).startLocation();
	}

	private void init() {
		//设置默认的一个经纬度,当后面定位完成后会覆盖
		BaseApplication application = BaseApplication.getInstance();
		XtomSharedPreferencesUtil.save(application, "lat", "43.792818");
		XtomSharedPreferencesUtil.save(application, "lng", "87.617733");
		XtomSharedPreferencesUtil.save(application, "address", "新疆维吾尔自治区乌鲁木齐市");
		XtomSharedPreferencesUtil.save(application, "province", "新疆维吾尔自治区");
		XtomSharedPreferencesUtil.save(application, "city", "乌鲁木齐市");
		XtomSharedPreferencesUtil.save(application, "area", "天山区");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(netChangeReceiver);
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {

	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {

	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case INIT:
				HemaArrayResult<SysInitInfo> sResult = (HemaArrayResult<SysInitInfo>) baseResult;
				SysInitInfo sysInitInfo = sResult.getObjects().get(0);
				getApplicationContext().setSysInitInfo(sysInitInfo);

				checkLogin();
				break;
			case CLIENT_LOGIN:
				HemaArrayResult<User> uResult = (HemaArrayResult<User>) baseResult;
				User user = uResult.getObjects().get(0);
				getApplicationContext().setUser(user);
				toMain();
				break;
		}
	}

	private void checkLogin() {
		if (isAutoLogin()) {
			if (getApplicationContext().getUser() != null) {
				getNetWorker().clientLogin();
			} else {
				toMain();
			}
		}else {
			toMain();
		}
	}

	// 检查是否自动登录
	private boolean isAutoLogin() {
		String autoLogin = XtomSharedPreferencesUtil.get(mContext, "autoLogin");
		boolean no = "no".equals(autoLogin);
		return !no;
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case INIT:
			//2016.10.31 start 客户要求，系统初始化失败之后，也可以进入首页
			showTextDialog("系统初始化失败\n请检查网络连接重试");
//            checkLogin();
            //2016.10.31 end
			break;
		case CLIENT_LOGIN:
			toMain();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case INIT:
			showTextDialog("获取系统初始化信息失败啦\n请检查网络连接重试");
			break;
		case CLIENT_LOGIN:
			// toLogin();
			toMain();
			break;
		default:
			break;
		}
	}

	private void toMain() {
//		String introductionShowed = XtomSharedPreferencesUtil.get(mContext,
//				"introductionShowed");
//		if (!"true".equals(introductionShowed)) {//第一次进入，启动引导页
		String isVirgin = XtomSharedPreferencesUtil.get(this, "isVirgin");
		boolean virgin = "false".equals(isVirgin);//非false，全部认为是第一次
		if (!virgin) {
			Intent it = new Intent(this, WelcomeActivity.class);
			startActivity(it);
		} else {
			Intent it = new Intent(this, MainActivity.class);
			startActivity(it);
		}
		finish();
	}

	@Override
	protected void findView() {
	}

	@Override
	protected void getExras() {
	}

	@Override
	protected void setListener() {
	}

    public BroadcastReceiver netChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
                ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                NetworkInfo activeInfo = manager.getActiveNetworkInfo();
                if (mobileInfo.isConnected() || wifiInfo.isConnected())
                    getNetWorker().init();
            }
        }
    };
}
